﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using IronOne.SalesOne.BusinessObjects;
using System.Configuration;
using Facade;
using System.Web.UI.HtmlControls;
using System.Collections.Specialized;

namespace IronOne.SalesOne.SalesOneWeb.BatchJobs
{
    public partial class JobScheduler : SOSecurityPage
    {
        BatchJob job;
        ConfiguraionFacade fac;

        protected void Page_Load(object sender, EventArgs e)
        {
            SetCredentials(ValidateUserCredentials(Request.Url.LocalPath));

            //registerControls();
            fac = new ConfiguraionFacade();

            if (!Page.IsPostBack)
            {
                populateJobs(fac.GetAvailableJobs());

                txtOneDate.Text = DateTime.Now.ToShortDateString();
                txtOneTime.Text = DateTime.Now.ToShortTimeString();
            }

            if (ddlJobList.SelectedIndex <= 0)
            {
                ddlScheduleType.Enabled = false;
                cbEnable.Enabled = false;
            }
        }

        private void SetCredentials(StringCollection credential)
        {
            foreach (string item in credential)
            {
                switch (item.ToLower())
                {
                    //case "c":
                    //    btnUpdate.Visible = true;
                    //    break;
                    case "u":
                        btnApply.Visible = true;
                        break;
                    /*case "d":
                        btnClear.Visible = true;
                        break;*/
                    case "v":
                        btnHistory.Visible = true;
                        break;
                    default:
                        break;
                }
            }
        }
        

        private void populateJobs(List<ListItem> jobList)
        {
            ddlJobList.DataSource = jobList;
            ddlJobList.DataTextField = "Text";
            ddlJobList.DataValueField = "Value";
            ddlJobList.DataBind();
            addDefaultItem(ddlJobList);
        }

        private void addDefaultItem(DropDownList ddl)
        {
            ListItem newItem = new ListItem("Select...","select");
            ddl.Items.Insert(0, newItem);
        }

        protected void btnApply_Click(object sender, EventArgs e)
        {
            job = new BatchJob();

            try
            {
                if (ddlJobList.SelectedIndex > 0 && Page.IsValid)
                //if (true)
                {
                    job.Schedule_Name = ddlJobList.SelectedValue;

                    job.FreqType = ddlScheduleType.SelectedValue == "onetime" ? 1 :
                        ddlScheduleType.SelectedValue == "sqlservice" ? 64 :
                        ddlOccurance.SelectedValue == "daily" ? 4 :
                        ddlOccurance.SelectedValue == "weekly" ? 8 :
                        rbAt.Checked ? 16 :
                        rbEvery.Checked ? 32 : 128;

                    job.Enabled = (Int16)(cbEnable.Checked ? 1 : 0);
                    /**/
                    if (ddlScheduleType.SelectedValue == "recurring")
                    {
                        if (rbEvery.Checked)
                        {
                            job.FreqSubdayType = int.Parse(ddlTimeType.SelectedValue);

                            job.ActiveStartTime = toTimeFormat(txtStartTime.Text);//
                            job.ActiveEndTime = toTimeFormat(txtEndTime.Text);//
                            job.FreqSubdayInterval = int.Parse(txtEvery.Text);
                        }
                        else
                        {
                            job.ActiveStartTime = toTimeFormat(txtAt.Text);//
                            //job.FreqSubdayInterval = int.Parse(txtEvery.Text);
                        }

                        if (ddlOccurance.SelectedValue == "monthly")
                        {
                            if (rbDay.Checked)
                            {
                                job.FreqInterval = int.Parse(txtDay.Text);
                                job.FreqRecurrenceFactor = int.Parse(txtRecMonths.Text);
                            }
                            else
                            {
                                job.FreqRelativeInterval = int.Parse(ddlRelative.SelectedValue);
                                job.FreqInterval = int.Parse(ddlType.Text);
                                job.FreqRecurrenceFactor = int.Parse(txtRecMonths1.Text);
                            }
                        }
                        else if (ddlOccurance.SelectedValue == "weekly")
                        {
                            job.FreqInterval = (cbSun.Checked ? 1 : 0) +
                                (cbMon.Checked ? 2 : 0) +
                                (cbTue.Checked ? 4 : 0) +
                                (cbWed.Checked ? 8 : 0) +
                                (cbThu.Checked ? 16 : 0) +
                                (cbFri.Checked ? 32 : 0) +
                                (cbSat.Checked ? 64 : 0);

                            job.FreqRecurrenceFactor = int.Parse(txtRecWeeks.Text);
                        }
                        else
                        {
                            job.FreqInterval = int.Parse(txtFreqDays.Text);
                        }

                        job.ActiveStartDate = toDateFormat(txtStartDate.Text);

                        if (!cbEndDate.Checked)
                            job.ActiveEndDate = toDateFormat(txtEndDate.Text);//
                    }
                    else if (ddlScheduleType.SelectedValue == "onetime")
                    {
                        job.ActiveStartDate = toDateFormat(txtOneDate.Text);//
                        job.ActiveStartTime = toTimeFormat(txtOneTime.Text);//
                    }

                    //fac = new ConfiguraionFacade();

                    if (fac.UpdateSchedule(job,User.Identity.Name))
                    {
                        MassageSummery("IIS401");
                    }
                    else
                    {
                        MassageSummery("IIS502");
                    }
                }
                else if (ddlJobList.SelectedIndex <= 0)
                {
                    MassageSummery("IIS503");
                }
                else if (!Page.IsValid)
                {
                    MassageSummery("IIS501");
                }
            }
            catch
            {
                MassageSummery("IIS514");
            }
        }

        private int toDateFormat(string p)
        {
            //p = p.Replace("/", "");
            //return int.Parse(p.Substring(4, 4) + p.Substring(0, 4));
            //DateTime dt = new DateTime(int.Parse(p.Split('/')[2]),int.Parse(p.Split('/')[0]),int.Parse(p.Split('/')[1]));
            string[] arr = p.Split('/');
            return int.Parse(arr[2] + (arr[1].Length == 1 ? "0" + arr[1] : arr[1]) + (arr[0].Length == 1 ? "0" + arr[0] : arr[0]));
        }

        private int toTimeFormat(string p)
        {
            return int.Parse(p.Replace(":",""));
        }


        protected void ddlJobList_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (ddlJobList.SelectedIndex > 0)
                {
                    job = fac.GetSchduleParams(ddlJobList.SelectedValue);
                    setControlState(job);
                    ddlScheduleType.Enabled = true;
                    cbEnable.Enabled = true;
                }
                else
                {
                    //error to select
                }
            }
            catch
            {
                MassageSummery("IIS514");
            }
        }

        private void setControlState(BatchJob j)
        {
            switch (j.FreqType)
            {
                case 1:
                    ddlScheduleType.SelectedValue = "onetime";
                    txtOneDate.Text = job.ActiveStartDate == null ? DateTime.Now.ToShortDateString() : toDate(job.ActiveStartDate.ToString());///
                    txtOneTime.Text = job.ActiveStartTime == 0 ? txtOneTime.Text : toTime(job.ActiveStartTime.ToString());///
                    break;
                case 64:
                    ddlScheduleType.SelectedValue = "sqlservice"; break;
                case 4:
                    ddlOccurance.SelectedValue = "daily";
                    ddlScheduleType.SelectedValue = "recurring";

                    txtFreqDays.Text = job.FreqInterval.ToString(); break;
                case 8:
                    ddlOccurance.SelectedValue = "weekly";
                    ddlScheduleType.SelectedValue = "recurring";

                    txtRecWeeks.Text = job.FreqRecurrenceFactor.ToString();

                    setDaysEnable(job.FreqInterval);
                    break;
                case 16:
                    ddlOccurance.SelectedValue = "monthly";
                    rbAt.Checked = true;
                    ddlScheduleType.SelectedValue = "recurring"; break;
                case 32:
                    ddlOccurance.SelectedValue = "monthly";
                    rbEvery.Checked = true;
                    ddlScheduleType.SelectedValue = "recurring"; break;
                default:
                    ddlScheduleType.SelectedValue = "recurring"; break;
            }

            cbEnable.Checked = job.Enabled == 1 ? true : false;

            if (ddlScheduleType.SelectedValue == "recurring")
            {
                txtStartDate.Text = job.ActiveStartDate == null ? DateTime.Now.ToShortDateString() : toDate(job.ActiveStartDate.ToString());///

                if (job.ActiveEndDate == 0)
                {
                    cbEndDate.Checked = true;
                }
                else
                {
                    cbEndDate.Checked = false;
                    txtEndDate.Text = job.ActiveEndDate == 99991231 ? DateTime.Now.ToShortDateString() : toDate(job.ActiveEndDate.ToString());
                }

                if (rbAt.Checked == true)
                {
                    txtAt.Text = job.ActiveStartTime == 0 ? txtAt.Text : toTime(job.ActiveStartTime.ToString());///
                }
                else
                {
                    ddlTimeType.SelectedValue = job.FreqSubdayType.ToString();
                    txtStartTime.Text = job.ActiveStartTime == 0 ? txtStartTime.Text : toTime(job.ActiveStartTime.ToString());///
                    txtEndTime.Text = job.ActiveEndTime == 235959 ? txtEndTime.Text : toTime(job.ActiveEndTime.ToString());
                    txtEvery.Text = job.FreqSubdayInterval.ToString();
                }

                if (ddlOccurance.SelectedValue == "monthly")
                {
                    if (job.FreqRelativeInterval == 0)
                    {
                        txtDay.Text = job.FreqInterval.ToString();
                        txtRecMonths.Text = job.FreqRecurrenceFactor.ToString();
                    }
                    else
                    {
                        ddlRelative.SelectedValue = job.FreqRelativeInterval.ToString();
                        ddlType.Text = job.FreqInterval.ToString();
                        txtRecMonths1.Text = job.FreqRecurrenceFactor.ToString();
                    }
                }
            }
        }

        private string toTime(string p)
        {
            p = p.Length == 5 ? "0" + p : p;            
            return p.Substring(0, 2) + ":" + p.Substring(2, 2) + ":" + p.Substring(4, 2);
        }

        private string toDate(string p)
        {
            return p.Substring(6, 2)+ "/" +int.Parse(p.Substring(4, 2))+ "/" +int.Parse(p.Substring(0, 4));
        }

        private void setDaysEnable(int value)
        {
            cbSat.Checked = value / 64 > 0 ? true : false;
            value = value % 64;
            cbFri.Checked = value / 32 > 0 ? true : false;
            value = value % 32;
            cbThu.Checked = value / 16 > 0 ? true : false;
            value = value % 16;
            cbWed.Checked = value / 8 > 0 ? true : false;
            value = value % 8;
            cbTue.Checked = value / 4 > 0 ? true : false;
            value = value % 4;
            cbMon.Checked = value / 2 > 0 ? true : false;
            value = value % 2;
            cbSun.Checked = value / 1 > 0 ? true : false;

        }

        protected void btnHistory_Click(object sender, EventArgs e)
        {
            if (ddlJobList.SelectedIndex > 0)
                Response.Redirect("~/BatchJobs/JobHistory.aspx?jobid=" + ddlJobList.SelectedItem.Text);
            else
                MassageSummery("IIS503");   
            
        }

        

        
    }
}
